package com.example.a2205douyin.register;

import androidx.annotation.NonNull;
import androidx.appcompat.app.AppCompatActivity;
import androidx.lifecycle.Observer;

import android.content.Intent;
import android.graphics.Color;
import android.os.Bundle;
import android.os.Handler;
import android.text.Editable;
import android.text.SpannableStringBuilder;
import android.text.Spanned;
import android.text.TextWatcher;
import android.text.method.LinkMovementMethod;
import android.text.style.ClickableSpan;
import android.text.style.ForegroundColorSpan;
import android.view.View;
import android.widget.Toast;

import com.blankj.utilcode.util.RegexUtils;
import com.blankj.utilcode.util.SPUtils;
import com.blankj.utilcode.util.ToastUtils;
import com.example.a2205douyin.MainActivity;
import com.example.a2205douyin.R;
import com.example.a2205douyin.baseMVVM.view.BaseActivity;
import com.example.a2205douyin.databinding.ActivityRegisterBinding;
import com.example.a2205douyin.entity.UserEntity;

import java.util.Random;
import java.util.Timer;
import java.util.TimerTask;

public class RegisterActivity extends BaseActivity<ActivityRegisterBinding,RegisterViewModel> {

    Handler handler = new Handler(){};
    Timer timer;
    int time = 60;//倒计时时间

    @Override
    protected void initData() {
        viewModel.success.observe(this, new Observer<UserEntity>() {
            @Override
            public void onChanged(UserEntity entity) {
                ToastUtils.showLong(entity.getMessage());
                if(entity.getCode()==200){
                 startActivity(new Intent(RegisterActivity.this, MainActivity.class));
                }
            }
        });
        viewModel.fail.observe(this, new Observer<String>() {
            @Override
            public void onChanged(String s) {
                ToastUtils.showLong(s);
            }
        });
    }

    @Override
    protected void initView() {
        //将复选框的内容设置为富文本格式
        //或许要修改的字符串
        String string = binding.cb.getText().toString();
        //将字符串的格式设为富文本格式
        SpannableStringBuilder builder = new SpannableStringBuilder(string);
        //添加文字颜色
        builder.setSpan(new ForegroundColorSpan(Color.RED),6,12, Spanned.SPAN_INCLUSIVE_INCLUSIVE);
        //添加点击事件
        ClickableSpan clickableSpan = new ClickableSpan() {
            @Override
            public void onClick(@NonNull View widget) {
                ToastUtils.showLong("点击了用户条框");
            }
        };
        builder.setSpan(clickableSpan,13,19,Spanned.SPAN_INCLUSIVE_INCLUSIVE);
        binding.cb.setMovementMethod(LinkMovementMethod.getInstance());//一定添加这一行，不然点击没有效果
        binding.cb.setText(builder);


        binding.register.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                String username = binding.etUsername.getText().toString();
                String password = binding.etPassword.getText().toString();
                String repassword = binding.etRepassword.getText().toString();
                if(username.isEmpty()||password.isEmpty()||repassword.isEmpty()){
                    ToastUtils.showLong("用户名和密码不能为空");
                }else if(!password.equals(repassword)){
                    ToastUtils.showLong("两次密码不一致");
                }else if(!RegexUtils.isMobileSimple(username)){
                    ToastUtils.showLong("用户名的格式应为手机号");
                }else if(!RegexUtils.isMatch("^[\\w]{6,8}$",password)){
                    ToastUtils.showLong("密码格式为6-8位的数字、字母、下划线");
                }else if(!binding.cb.isChecked()){
                    ToastUtils.showLong("您未同意用户隐私和用户条款协议");//自行引申  弹出自定义对话框 ，同意后进行登录操作 不同意，不勾选复选框
                } else if (!binding.code.getText().toString().equals(SPUtils.getInstance().getString("code"))) {
                    ToastUtils.showLong("验证码不正确，请重新输入或者获取");
                } else{
                    //等待添加正则的校验--手机号和数字字母组合的密码
                    viewModel.register(username,password,repassword);
                }
            }
        });
        //默认注册按钮不可用
        binding.register.setEnabled(false);
        binding.getCode.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                //获取随机数
                //int i = new Random().nextInt(9999);//暂时设置不完美，可能会出现9 或者99的情况，可以自行处理一下
                StringBuilder sb = new StringBuilder();
                for (int i = 0; i < 4; i++) {
                    int i1 = new Random().nextInt(9);
                    sb.append(i1+"");
                }
                Toast.makeText(RegisterActivity.this, ""+sb.toString(), Toast.LENGTH_SHORT).show();
                //为了确认输入的是正确的验证码，将验证码保存在sp中
                SPUtils.getInstance().put("code",sb.toString());
                //如果涉及到验证码有效期的话，可以发送验证码的时间保存下来，点击注册时，用当前时间-发送时间<规定时间则进行注册操作，否则提示验证码已超时，请重新获取
                //启动定时任务
                timer = new Timer();
                timer.schedule(new TimerTask() {
                    @Override
                    public void run() {
                        handler.post(new Runnable() {
                            @Override
                            public void run() {
                                binding.getCode.setText(time--+"秒");
                                if(time==0){
                                    binding.getCode.setText("获取验证码");
                                    timer.cancel();
                                    time=60;//倒计时回到60，重新开始计数
                                }
                            }
                        });
                    }
                },0,1000);
            }
        });
        //当验证码输入为4位时，注册按钮恢复使用
        binding.code.addTextChangedListener(new TextWatcher() {
            @Override
            public void beforeTextChanged(CharSequence s, int start, int count, int after) {

            }

            @Override
            public void onTextChanged(CharSequence s, int start, int before, int count) {
                if(binding.code.getText().toString().length()==4){
                    binding.register.setEnabled(true);
                }else {
                    binding.register.setEnabled(false);
                }
            }

            @Override
            public void afterTextChanged(Editable s) {

            }
        });

    }

    @Override
    protected Class<RegisterViewModel> getViewModel() {
        return RegisterViewModel.class;
    }

    @Override
    protected int getLayout() {
        return R.layout.activity_register;
    }
}